//下面是搜索栏事件
const keywordBtn=document.querySelector('.keyword')
const searchList=document.querySelector('.search-nextbox')

function callBackData(res){
    if(!res.g) {
        searchList.style.display= 'none'
        return 
    }
    let str = ''
    res.g.forEach(item => {
      str += `
        <li>${ item.q }</li>
      `
    })
    searchList.innerHTML = str
    searchList.style.display = 'block'
    keywordBtn.addEventListener('blur',()=>{
    searchList.style.display = 'none'
    })
}

function searchHandler(){
    keywordBtn.addEventListener('input',()=>{
        const scriptType=document.createElement('script')
        const text = keywordBtn.value.trim()
        scriptType.src=`https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=35106,31253,35237,35435,34584,35246,34872,35316,26350&wd=${text}&req=2&bs=%E7%99%BE%E5%BA%A6&csor=7&pwd=asdas&cb=callBackData&_=1639482112387`
        document.body.appendChild(scriptType);
        scriptType.remove()
        
    })
}

//判断是否是有没有商品id
const did = window.sessionStorage.getItem("did")
if (!did) window.location.href = "./index.html"

// 本页面最主要
init()
function init() {
    bindHtml()
    clientBox()
    searchKeyword()
    leftMenu()
    actions()
    searchHandler()

    toIndex()
}

function clientBox() {
    const clientServer = document.querySelector('.menu2 >ul')
    pAjax({
        url: 'https://www.lemall.com/api/news/footerNews.html',
        dataType: 'json'
    }).then(res => {
        let str = '';
        res.data.forEach(item => {
            str += `
        <li><a>${ item.name}</a></li>
`
        })
        clientServer.innerHTML = str;
    })
}

function searchKeyword() {
    const hotwords = document.querySelector('.hotwords')
    pAjax({
        url: 'https://www.lemall.com/api/searchKeyword.html',
        dataType: 'json'
    }).then(res => {
        let str = ``;
        str += `
        <b>热门搜索:</b>
        <div>
        `
        res.data.forEach(item => {
            str += `
                <a>${item}</a>
                `
        })
        str += `</div>`;
        hotwords.innerHTML = str;
    })
}

function leftMenu() {
    const indexGate = document.querySelector('.leftmenu>ul')
    pAjax({
        url: 'https://www.lemall.com/api/indexCate.html',
        dataType: 'json'
    }).then(res => {
        let str = '';
        res.data.cateList.forEach(item => {
            str += `
                <li>
                <a>${item.name}</a>
                <b>></b>
                <div class="nextmenu">
                <dl>
                `
            item.childs.forEach(item => {
                str += `
                    <dt>
                        <a>${item.name}</a>
                        <span>></span>
                    </dt>
                    `
                str += `
                        <dd>`
                item.childs.forEach(item => {
                    str += `
                            <a>${item.name}</a>
                  
                    `
                })
                str += `  </dd>
                    `
            })
            str += `
                        </dl>
                     </div>
                     </li>
                     `
        })
        indexGate.innerHTML = str;
    })
}

function actions() {
    const allGoods = document.querySelector(".leftmenu")
    const allGoodsBtn = document.querySelector('.navigator .first')
    const icon = document.querySelector('.navigator .first>i')
    allGoodsBtn.addEventListener('mouseover', () => {
        allGoods.classList.add("active")
        icon.classList.add("active")
    })
    allGoodsBtn.addEventListener('mouseout', () => {
        allGoods.classList.remove("active")
        icon.classList.remove("active")
    })
}

//以上通用部分

//页面渲染部分
//判断是否是点击商品详情点击过来的
function bindHtml() {
    
    pAjax({
        url: 'https://www.lemall.com/api/product/detail.html',
        data: {
            productId: did
        },
        dataType: 'json'
    }).then(res => {
        if(!res.success){
            alert('获取信息失败, 未获取到商品id,确认返回主页')
            window.location.href="./index.html"
        }
        const title = document.querySelector(".detailbox .title")

        if(res.data.productCate){
            let str = ``;
            str += `
            <b>${res.data.productCate.name}<i>></i></b>
            <span>${res.data.productCateP.name}<i>></i></span>
            <span>${res.data.productCatePP.name}<i>></i></span>
            <span>乐视<i>></i></span>
            <em>${res.data.product.name1}</em>
            `
            title.innerHTML = str;
        }else{
            title.style.display='none'
        }
       


        const goodsPriceBox = document.querySelector(".goodsPriceBox")
        let str1 = ``;
        str1 += `
        <p class="gooods-title">${res.data.product.name1}</p>
        <div class="pricebox">
            <span>商&nbsp;城&nbsp;价</span>
            <h3>￥${res.data.product.mallPcPrice}</h3>
            <span>市&nbsp;场&nbsp;价</span>
            <em>￥${res.data.product.marketPrice}</em>
            <div>
                <p>累积评价</p>
                <a>${res.data.product.commentsNumber}</a>
            </div>
        </div>

        `;
        const stockBox=document.querySelector(".stock")
        let str3=``;
            str3+=`
            <p>(库存剩余<span>${res.data.product.productStock}</span>件)</p>
            `
            stockBox.innerHTML=str3;
        goodsPriceBox.innerHTML = str1
        const enlargeList = document.querySelector('.enlarge')
        let str2 = ``;

        str2 += `
        <div class="top show">
            <img src="${res.data.product.masterImg}" alt="">
        <div class="mask"></div>
    </div>
            <div class="bottom">
        <ul class="list">
            `
            res.data.productLeadPicList.forEach(item=>{
                str2+=`
                    <li data-imgurl="${item}"><img src="${item}" alt=""></li>
                `
            })
            str2+=`
          
        </ul>
     </div>
        <div class="enlargebox">
        <img src="${res.data.product.masterImg}"
        width="800px" height="800px">
    </div>

    
    </div>
        `
        enlargeList.innerHTML=str2 ;   
        new Enlarge(".enlarge")
        handler()
    })
}
//页面中的事件
//点击加入购物车
function handler(){
    const countBox = document.querySelector('.choose')
    const countBtn = document.querySelector('.count')
    const buyBox = document.querySelector('.buy')
    let count = countBtn.value - 0;
    const stockNum= document.querySelector('.stock>p>span').innerHTML-0
    countBox.addEventListener('input',e=>{
        if(e.target.className==='count') {
            count=countBtn.value - 0;
            if(isNaN(count)) count=1
            count=count<1?1:count
            count= count>stockNum?stockNum:count
            countBtn.value=count
        }
    })
    countBox.addEventListener('click',e=>{
        if(e.target.value==="+") count++
        if(e.target.value==="-") count--
        count=count<1?1:count
        count= count>stockNum?stockNum:count
        countBtn.value=count
    })
    buyBox.addEventListener('click',e=>{
        if(e.target.className==="buynow")alert('没钱')
        if(e.target.className==="toshopcart"){
            goodsId=did-0;
            goodsId?toShopCart(goodsId):alert('商品失效了, 请重试')
        }
        
    })
//滑动切换放大镜图片
    const topBox = document.querySelector(".show")
    const bottomBox = document.querySelector(".bottom>.list")
    const enlargeBox = document.querySelector(".enlargebox")
    bottomBox.addEventListener('mouseover',e=>{
        if(e.target.nodeName==="LI"){
           const imgurl= e.target.dataset.imgurl
           topBox.firstElementChild.src=imgurl;
           enlargeBox.firstElementChild.src=imgurl;

        }
    })
}


function toIndex(){
    const logoBox= document.querySelector('.logo')
    logoBox.addEventListener('click',()=>{
        window.location.href="./index.html"
    })
}


